import 'package:boss/color_constant.dart';
import 'package:boss/main.dart';
import 'package:boss/models/pay_qr_code.dart';
import 'package:boss/provider/binding_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/pay/payList/modal/pay_qr_code_modal.dart';
import 'package:boss/ui/page/pay/payList/pay_edit_describe_page.dart';
import 'package:boss/ui/page/pay/payQrApply/pay_qr_apply_page.dart';
import 'package:boss/ui/page/pay/payScan/pay_scan_page.dart';
import 'package:boss/ui/widget/button/radius_button.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/custom_divier.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:boss/ui/widget/shadow_radius_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:router/annotation.dart';
import 'package:async/async.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:boss/ui/widget/popupMenu/popupMenu.dart' as popupMenu;

@RouterConfig(PayListPage.pageName)
class PayListPage extends StatefulWidget {
  static const pageName = '/PayListPage';

  @override
  _PayListPageState createState() => _PayListPageState();
}

class _PayListPageState extends BaseState<PayListPage> {
  _PayListPageState() : super(PayListPage.pageName);

  List<PayQrCode> items = [];

  int get page => items.length ~/ 10;

  List<String> menus = ['绑定实体二维码', '申请二维码'];
  List<String> menuIcons = ['assets/image/pay_list_bind.png', 'assets/image/pay_list_qr_code.png'];

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: items.isEmpty ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.light,
      child: Scaffold(
        appBar: items.isEmpty
            ? null
            : CenterTitleAppBar(
                title: '收款码管理',
                actions: [
                  popupMenu.PopupMenuButton(
                    items: menus,
                    popupWidth: 330.w,
                    itemBuilder: (context, index) {
                      return Container(
                        height: 90.w,
                        padding: EdgeInsets.symmetric(horizontal: 30.w),
                        child: Column(
                          children: [
                            Expanded(
                              child: Row(
                                children: [
                                  Container(
                                    child: BaseImage(menuIcons[index], width: 34.w, height: 34.w),
                                    margin: EdgeInsets.only(right: 10.w),
                                  ),
                                  Text(menus[index], style: TextStyleConstant().normal_1_28)
                                ],
                              ),
                            ),
                            if (index < menus.length - 1) CustomDivider(),
                          ],
                        ),
                      );
                    },
                    onItemTap: (index) {
                      if (index == 0) {
                        Navigator.pushNamed(context, PayScanPage.pageName);
                      } else if (index == 1) {
                        Navigator.pushNamed(context, PayQrApplyPage.pageName);
                      }
                    },
                    child: LabelButton(
                      title: '新增',
                      padding: EdgeInsets.all(4),
                      textStyle: TextStyleConstant().blue_28,
                    ),
                  ),
                ],
              ),
        body: LoaderPullRefresh<PayQrCode>(
          loadTask: loadTask,
          refreshTask: refreshTask,
          builder: (context) {
            if (items.isEmpty) {
              return _EmptyView();
            }

            return ListView.builder(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              itemBuilder: (context, index) {
                final current = items[index];

                return _Item(
                  current,
                  onTap: () {
                    showPayQrCodeModal(context, current.qrcodeUrl);
                  },
                  onEditTap: () async {
                    final current = items[index];
                    final res = await Navigator.pushNamed(context, PayEditDescribePage.pageName, arguments: {'data': current});
                    if (res != null) {
                      setState(() {
                        current.describe = res;
                      });
                    }
                  },
                );
              },
              itemCount: items.length,
            );
          },
        ),
      ),
    );
  }

  Future<Result<List<PayQrCode>>> loadTask() async {
    return queryData(1);
  }

  Future<Result<List<PayQrCode>>> refreshTask() async {
    return queryData(page + 1);
  }

  Future<Result<List<PayQrCode>>> queryData(int page) async {
    final res = await api.queryPayQrCode(page, 10);
    if (!res.successful()) {
      return Result.error(res.msg);
    }
    if (page == 1) {
      items = res.data.items;
    } else {
      items.addAll(res.data.items);
    }
    setState(() {});
    return Result.value(res.data.items);
  }
}

class _Item extends StatelessWidget {
  final PayQrCode data;
  final VoidCallback onTap;
  final VoidCallback onEditTap;

  const _Item(this.data, {this.onTap, this.onEditTap, Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ShadowRadiusCard(
      padding: EdgeInsets.all(20.w),
      margin: EdgeInsets.only(top: 30.w),
      child: Row(
        children: [
          Expanded(
            child: Column(
              children: [
                buildRow('二维码编号：', data.qrcode),
                buildRow('绑定时间：', flustars.DateUtil.formatDateStr(data.btime, format: 'yyyy/MM/dd')),
                buildRow('申请方式：', data.applyTypeText),
                buildRow('备       注：', data.describe, isEdit: true),
              ],
            ),
          ),
          RadiusButton(
            title: '查看',
            width: 120.w,
            height: 50.w,
            margin: EdgeInsets.only(left: 20.w),
            textStyle: TextStyleConstant().white_28.copyWith(height: 1.2),
            onTap: onTap,
          )
        ],
      ),
    );
  }

  Widget buildRow(String title, String value, {bool isEdit = false}) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.w),
      child: Row(
        children: [
          Container(
            width: 180.w,
            child: Text(title, style: TextStyleConstant().normal_2_28),
          ),
          Expanded(
            child: GestureDetector(
              onTap: () {
                if (isEdit && onEditTap != null) {
                  onEditTap();
                }
              },
              child: RichText(
                text: TextSpan(
                  text: value,
                  style: TextStyleConstant().normal_1_28,
                  children: [
                    if (isEdit) TextSpan(text: '编辑', style: TextStyleConstant().blue_28),
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

class _EmptyView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final safeTop = MediaQuery.of(context).padding.top;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 350.w + safeTop,
          padding: EdgeInsets.only(top: safeTop),
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/image/pay_code_header_bg.png'),
              fit: BoxFit.fitHeight,
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      behavior: HitTestBehavior.translucent,
                      child: Container(
                        padding: EdgeInsets.only(left: 30.w, right: 30.w, top: 30.w, bottom: 30.w),
                        alignment: Alignment.centerLeft,
                        child: BaseImage(
                          'assets/image/arrow_left_icon.png',
                          width: 16.w,
                          height: 34.w,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    Text('收款码管理', style: TextStyleConstant().white_36.copyWith(fontWeight: FontWeight.w500)),
                    SizedBox(width: 76.w),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 30.w, top: 40.w, bottom: 10.w),
                child: Text('静态收款码', style: TextStyleConstant().white_36.copyWith(fontWeight: FontWeight.w500)),
              ),
              Container(
                width: 610.w,
                margin: EdgeInsets.only(left: 30.w),
                child: Text(
                  '顾客用微信/支付宝扫描收款码付款，交易金额将会结算给 该门店账户。',
                  style: TextStyleConstant().white_24.copyWith(height: 1.6),
                ),
              ),
            ],
          ),
        ),
        _ListTitleRow(
          title: '绑定实体二维码',
          subTitle: '联系工作人员发送的实体收款码，在此进行扫码绑定',
          btnText: '扫码绑定',
          onTap: () async {
            try {
              showLoadingToast();

              final provider = Provider.of<BindingProvider>(context, listen: false);

              await provider.initData();

              if (provider.payInfoForm.id != null) {
                Navigator.pushNamed(context, PayScanPage.pageName);
              } else {
                toast('请先填写收款账户');
              }
            } finally {
              hideLoadingToast();
            }
          },
        ),
        _ListTitleRow(
          title: '申请收款码',
          subTitle: '二维码下载后可直接用于收款，无需再进行绑定',
          btnText: '申   请',
          onTap: () {
            Navigator.pushNamed(context, PayQrApplyPage.pageName);
          },
        ),
      ],
    );
  }
}

class _ListTitleRow extends StatelessWidget {
  final String title;
  final String subTitle;
  final String btnText;
  final VoidCallback onTap;

  const _ListTitleRow({this.title, this.subTitle, this.btnText, this.onTap, Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ShadowRadiusCard(
      width: double.infinity,
      height: 200.w,
      margin: EdgeInsets.only(left: 20.w, right: 20.w, top: 30.w),
      padding: EdgeInsets.all(30.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(title, style: TextStyleConstant().normal_1_34),
          Text(subTitle, style: TextStyleConstant().normal_1_24),
          RadiusButton(
            title: btnText,
            width: 160.w,
            height: 50.w,
            textStyle: TextStyleConstant().white_28,
            onTap: onTap,
          )
        ],
      ),
    );
  }
}
